package com.edeweiss.community.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/*
* 抽取公共的servlet
* */
@WebServlet(name = "BaseServlet")
public class BaseServlet extends HttpServlet {
    @Override
    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        //获取方法名
        String method = request.getParameter("method");

        if (method == null && "".equals(method) && "".equals(method.trim())) {
            method = "defalutMethod";
        }

        //得到子类字节码文件
        Class clazz = this.getClass();

        try {
            //获取对应的方法
            Method mt = clazz.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            if (mt != null) {
                //执行此方法
                String url = (String)mt.invoke(this, request, response);
                if (url != null) {
                    request.getRequestDispatcher(url).forward(request,response);
                } else{

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    //默认方法
    public String defaultMethod(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        return null;
    }
}
